import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/Reply.dart';
import 'package:flutter_chip/bean/Topic.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/database/db_praise.dart';
import 'package:flutter_chip/utils/comm_utils.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/widget/RouteSlide.dart';
import 'package:flutter_chip/widget/view_image.dart';
import 'package:flutter_chip/widget/view_loading.dart';
import 'package:flutter_chip/widget/widget_comm.dart';
import 'package:provide/provide.dart';

class ForumInfoPage extends StatefulWidget {
  final String topicId;

  ForumInfoPage(this.topicId);

  @override
  _ForumInfoPageState createState() => _ForumInfoPageState();
}

class _ForumInfoPageState extends State<ForumInfoPage> {
  var _item = [];
  var textController = TextEditingController();
  bool _isEdit = false;
  bool _loading = false;
  Topic _topic;
  User user;
  String _msg = "加载中...";
  bool isFollow = false;

  //数据库
  PraiseDao _praiseDao = PraiseDao();

//所有点赞列表
  Set<String> _praiseSets;

  @override
  void initState() {
    super.initState();
    _getTopic();
    _getReplys();
  }

  @override
  Widget build(BuildContext context) {
    user = Provide.value<User>(context);
    return Scaffold(
      backgroundColor: Colors.white,
      body: ProgressDialog(
        msg: _msg,
        loading: _loading,
        child: GestureDetector(
            child: Column(children: <Widget>[
              Expanded(
                child: NestedScrollView(
                  headerSliverBuilder: _headerSliver,
                  body: Container(height: 10),
                ),
              ),
              _showSendWidget()
            ]),
            onTap: () {
              setState(() {
                if (_isEdit) {
                  _isEdit = false;
                }
              });
            }),
      ),
    );
  }

  List<Widget> _headerSliver(BuildContext context, bool innerBoxIsScrolled) {
    return <Widget>[
      SliverAppBar(
        backgroundColor: Colors.white,
        automaticallyImplyLeading: true,
        centerTitle: true,
        title: Text(
          '详情',
          style: TextStyle(fontSize: 18),
        ),
        pinned: true,
        actions: <Widget>[
          IconButton(icon: Icon(Icons.more_vert), onPressed: () {}),
        ],
      ),
      _userWidget(),
      _titleWidget(),
      _contentWidget(),
      SliverToBoxAdapter(child: Container(color: Colors.white, height: 8)),
      _picWidget(),
      _resourceWidget(),
      _bottomWidget(),
      SliverToBoxAdapter(child: Container(color: Color(0xffdddddd), height: 8)),
      _replyBarWidget(),
      _replyListWidget()
    ];
  }

  ///用户信息
  Widget _userWidget() {
    bool _isSelf = false;
    if (null != user &&
        null != _topic &&
        null != user.userId &&
        user.userId == _topic.userId) {
      _isSelf = true;
    }
    Widget _nameWidget = Container();
    if (null != _topic && null != _topic.userName) {
      _nameWidget = Text(
        _topic.userName,
        style: TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.bold,
        ),
      );
    }
    return SliverToBoxAdapter(
      child: Row(children: <Widget>[
        Container(
          width: 32,
          height: 32,
          margin: EdgeInsets.all(10),
          child: ClipOval(
            child: CachedNetworkImage(
              imageUrl: Api.getUrl(null != _topic ? _topic.imgUrl : ''),
              fit: BoxFit.cover,
              errorWidget: (context, url, error) =>
                  Image.asset(Comm.IMG_DEFAULT, fit: BoxFit.cover),
            ),
          ),
        ),
        Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
          _nameWidget,
          Text(
            null != _topic ? '${CommUtil.getTimeDiff(_topic.createAt)}' : '',
            style: TextStyle(color: Colors.grey, fontSize: 12),
          )
        ]),
        Expanded(
          child: Container(),
          flex: 1,
        ),
        Offstage(
          offstage: _isSelf,
          child: GestureDetector(
            child: Container(
              height: 24,
              alignment: Alignment.center,
              margin: EdgeInsets.only(right: 20),
              padding: EdgeInsets.only(left: 6, right: 6),
              decoration: BoxDecoration(
                  color: Colors.lightBlue,
                  borderRadius: BorderRadius.circular(4)),
              child: Text(
                isFollow ? "√已关注" : '+关注',
                style: TextStyle(color: Colors.white, fontSize: 14),
              ),
            ),
            onTap: () {
              _followUser();
            },
          ),
        )
      ]),
    );
  }

  ///标题
  Widget _titleWidget() {
    Widget child;
    if (null == _topic || null == _topic.title || _topic.title.isEmpty) {
      child = SizedBox(height: 10);
    } else {
      child = Container(
        margin: EdgeInsets.only(left: 10, top: 6, bottom: 6),
        child: Text(
          _topic.title,
          style: TextStyle(
              color: Color(0xff333333),
              fontWeight: FontWeight.bold,
              fontSize: 16),
        ),
      );
    }
    return SliverToBoxAdapter(
      child: child,
    );
  }

  ///内容
  Widget _contentWidget() {
    return SliverToBoxAdapter(
      child: Container(
        margin: EdgeInsets.only(left: 10),
        child: Text(
          null != _topic ? _topic.content : "",
          style: TextStyle(color: Color(0xff333333), fontSize: 16),
        ),
      ),
    );
  }

  ///显示图片
  Widget _picWidget() {
    bool showPic = null != _topic &&
        null != _topic.imageUrls &&
        _topic.imageUrls.isNotEmpty;
    Widget picWidget;
    if (!showPic) {
      return SliverToBoxAdapter(
          child: Container(color: Colors.white, height: 8));
    } else {
      List<String> images = _topic.imageUrls.split(",");
      List<Widget> childs = images.map((item) {
        BorderRadius borderRadius;
        if (images.length == 1) {
          borderRadius = BorderRadius.circular(6);
        } else if (item == images.first) {
          borderRadius = BorderRadius.only(
              topLeft: Radius.circular(6),
              topRight: Radius.circular(6),
              bottomLeft: Radius.circular(0),
              bottomRight: Radius.circular(0));
        } else if (item == images.last) {
          borderRadius = BorderRadius.only(
              topLeft: Radius.circular(0),
              topRight: Radius.circular(0),
              bottomLeft: Radius.circular(6),
              bottomRight: Radius.circular(6));
        } else {
          borderRadius = BorderRadius.circular(0);
        }
        double picWidth = MediaQuery.of(context).size.width - 20;
        return GestureDetector(
            child: Container(
              width: picWidth,
              margin: EdgeInsets.only(bottom: 10),
              child: ClipRRect(
                borderRadius: borderRadius,
                child: CachedNetworkImage(
                  imageUrl: Api.getUrl(item),
                  fit: BoxFit.cover,
                  errorWidget: (context, url, error) => CommWidget.imgError(),
                ),
              ),
            ),
            onTap: () {
              int current = images.indexOf(item);
              Navigator.of(context).push(
                RouteSlide(
                  ImagePage(images, current: current),
                ),
              );
            });
      }).toList();
      picWidget = Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween, children: childs);
      return SliverToBoxAdapter(
        child: picWidget,
      );
    }
  }

  ///分类显示
  Widget _resourceWidget() {
    if (null == _topic || null == _topic.typeDesc) {
      return SliverToBoxAdapter(
        child: Container(
          height: 0,
          color: Colors.white,
        ),
      );
    }
    return SliverToBoxAdapter(
      child: Row(
        children: <Widget>[
          Container(
            alignment: Alignment.center,
            padding: EdgeInsets.only(left: 4, right: 4, top: 2, bottom: 2),
            margin: EdgeInsets.all(10),
            decoration: BoxDecoration(
                color: Color(0xffE6FAF3),
                borderRadius: BorderRadius.circular(2)),
            child: Text(
              _topic.typeDesc,
              style: TextStyle(color: Color(0xff333333), fontSize: 12),
            ),
          )
        ],
      ),
    );
  }

  ///底部按钮
  Widget _bottomWidget() {
    bool isPraise = null != _topic &&
        null != _praiseSets &&
        _praiseSets.contains(_topic.topicId);
    Color colorPraise = isPraise ? Colors.redAccent : Color(0xff999999);
    TextStyle stylePraise = TextStyle(color: colorPraise);

    int replyCount = null == _topic ? 0 : _topic.repayCount;
    int praiseCount = null == _topic ? 0 : _topic.praiseCount;
    return SliverToBoxAdapter(
      child: Container(
        child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              GestureDetector(
                  child: Row(children: <Widget>[
                    Icon(Icons.share, size: 18, color: Color(0xff999999)),
                    SizedBox(width: 4),
                    Text('分享', style: TextStyle(color: Color(0xff999999)))
                  ]),
                  onTap: () {}),
              SizedBox(width: 16),
              GestureDetector(
                  child: Row(children: <Widget>[
                    Icon(Icons.speaker_notes,
                        size: 18, color: Color(0xff999999)),
                    SizedBox(width: 4),
                    Text('$replyCount',
                        style: TextStyle(color: Color(0xff999999)))
                  ]),
                  onTap: () {}),
              SizedBox(width: 16),
              GestureDetector(
                  child: Row(children: <Widget>[
                    Icon(Icons.thumb_up, size: 18, color: colorPraise),
                    SizedBox(width: 4),
                    Text('$praiseCount', style: stylePraise)
                  ]),
                  onTap: () async {
                    if (!isPraise) {
                      _praiseDao.insert(_topic.topicId);
                      _praiseSets = await _praiseDao.queryAll();
                      _update(_topic.topicId, 1);
                      setState(() {
                        _topic.isPraise = true;
                        _topic.praiseCount++;
                      });
                    } else {
                      _praiseDao.delPraise(_topic.topicId);
                      _praiseSets = await _praiseDao.queryAll();
                      _update(_topic.topicId, -1);
                      setState(() {
                        _topic.isPraise = false;
                        if (_topic.praiseCount > 0) {
                          _topic.praiseCount--;
                        }
                      });
                    }
                  }),
            ]),
        margin: EdgeInsets.only(left: 10, right: 10, bottom: 10),
      ),
    );
  }

  ///留言标题栏
  Widget _replyBarWidget() {
    return SliverToBoxAdapter(
      child: Container(
        padding: EdgeInsets.all(10),
        child: Row(children: <Widget>[
          Text('最新留言', style: TextStyle(fontSize: 16)),
          Expanded(child: Container()),
          GestureDetector(
            child: Container(
              height: 28,
              alignment: Alignment.center,
              padding: EdgeInsets.only(left: 4, right: 4),
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.deepOrange, width: 1),
                  borderRadius: BorderRadius.circular(4)),
              child: Row(children: <Widget>[
                Icon(
                  Icons.edit,
                  size: 14,
                  color: Colors.deepOrange,
                ),
                Text(
                  '写留言',
                  style: TextStyle(color: Colors.deepOrange),
                )
              ]),
            ),
            onTap: () {
              setState(() {
                _isEdit = !_isEdit;
              });
            },
          ),
        ]),
      ),
    );
  }

  ///留言列表
  Widget _replyListWidget() {
    if (_item.isEmpty) {
      return SliverToBoxAdapter(
        child: CommWidget.nullWidget(msg: '还没有人评论,还不快来抢沙发~'),
      );
    } else {
      return SliverList(
          delegate:
              SliverChildBuilderDelegate((BuildContext context, int index) {
        Reply gdsMsg = _item[index];
        return _itemGdsMsgWidget(gdsMsg);
      }, childCount: _item.length));
    }
  }

  ///留言列表item
  Widget _itemGdsMsgWidget(Reply reply) {
    //作者标记
    Widget authorWidget = Container(width: 1, height: 1);
    if (null != _topic && _topic.userId == reply.userId) {
      authorWidget = Container(
        margin: EdgeInsets.only(bottom: 6, left: 4),
        padding: EdgeInsets.only(left: 2, right: 2),
        decoration: BoxDecoration(
            border:
                Border.all(color: Theme.of(context).accentColor, width: 0.5),
            borderRadius: BorderRadius.circular(2)),
        child: Text(
          '作者',
          style: TextStyle(color: Theme.of(context).accentColor, fontSize: 10),
        ),
      );
    }
    //刪除按钮
    Widget delWidget = Container(width: 1, height: 1);
    if (null != user && user.userId == reply.userId) {
      delWidget = GestureDetector(
        child: Text(
          '删除',
          style: TextStyle(color: Colors.grey, fontSize: 12),
        ),
        onTap: () => showMsgDialog(context, reply.replyId),
      );
    }
    return Container(
      margin: EdgeInsets.all(10),
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            Row(children: <Widget>[
              GestureDetector(
                  child: Row(children: <Widget>[
                    Container(
                        width: 30,
                        height: 30,
                        margin: EdgeInsets.only(bottom: 6),
                        child: ClipOval(
                            child: CachedNetworkImage(
                          imageUrl: Api.getUrl(reply.imgUrl),
                          fit: BoxFit.cover,
                          errorWidget: (context, url, error) =>
                              Image.asset(Comm.IMG_DEFAULT, fit: BoxFit.cover),
                        ))),
                    Container(
                        margin: EdgeInsets.only(left: 6, bottom: 6),
                        child: Text(reply.userName,
                            style: TextStyle(fontWeight: FontWeight.bold)))
                  ]),
                  onTap: () {
                    Routers.router.navigateTo(context,
                        '${Routers.PAGE_USERINFO}?userId=${reply.userId}',
                        transition: TransitionType.inFromRight);
                  }),
              authorWidget,
              Expanded(flex: 1, child: Container()),
              delWidget
            ]),
            Container(
                margin: EdgeInsets.only(left: 36), child: Text(reply.content)),
            Container(
              margin: EdgeInsets.only(left: 36, top: 6),
              child: Text(CommUtil.getTimeDiff(reply.createAt),
                  style: TextStyle(color: Color(0xffaaaaaa))),
            )
          ]),
    );
  }

  ///留言输入框
  Widget _showSendWidget() {
    return Offstage(
      offstage: !_isEdit,
      child: Container(
        height: 64,
        color: Color(0xffEEEEEE),
        padding: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
        child: Container(
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.only(left: 10),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(22), color: Colors.white),
            child: TextField(
              controller: textController,
              decoration: InputDecoration(
                  suffixIcon: IconButton(
                      icon: Icon(Icons.send),
                      onPressed: () {
                        FocusScope.of(context).requestFocus(FocusNode());
                        _sendReply();
                      }),
                  border: OutlineInputBorder(borderSide: BorderSide.none),
                  hintText: '输入留言',
                  contentPadding: EdgeInsets.only(left: 10)),
            )),
      ),
    );
  }

  ///获取话题详情
  Future _getTopic() async {
    setState(() {
      _msg = "加载中...";
      _loading = true;
    });
    _praiseSets = await _praiseDao.queryAll();
    String url = "${Api.URL_TOPIC_INFO}?topicId=${widget.topicId}";
    Http.get(url, successCallBack: (data) {
      setState(() {
        _loading = false;
        _topic = Topic.fromJson(json.decode(data));
      });
      _isFollow();
    });
  }

  ///获取留言列表
  Future _getReplys() async {
    String url = "${Api.URL_REPLY_LIST}?topicId=${widget.topicId}";
    print("获取留言列表：$url");
    await Http.get(url, successCallBack: (data) {
      List list =
          json.decode(data)["replys"].map((m) => Reply.fromJson(m)).toList();
      _item.clear();
      setState(() {
        if (null != _topic) {
          _topic.repayCount = json.decode(data)["replyCount"];
          _topic.praiseCount = json.decode(data)["praiseCount"];
        }
        _item.addAll(list);
      });
    }, errorCallBack: (error) {
      Toast.show(error);
    });
  }

  ///发表留言
  void _sendReply() async {
    if (textController.text.isEmpty) {
      Toast.show("内容不能为空");
      return;
    }
    if (!Comm.isLogin) {
      Toast.show("请先登录");
      return;
    }
    setState(() {
      _isEdit = false;
      _loading = true;
      _msg = "留言中...";
    });
    Map<String, String> params = Map();
    params['topicId'] = _topic.topicId;
    params['content'] = textController.text;

    Http.post(Api.URL_REPLY_ADD, params: params, successCallBack: (data) {
      _getReplys();
      setState(() {
        textController.value = TextEditingValue(text: '');
        _loading = false;
      });
    }, errorCallBack: (msg) {
      setState(() {
        _loading = false;
      });
      Toast.show(msg);
    });
  }

  ///信息提示对话框
  void showMsgDialog(BuildContext context, String replyId) {
    showCupertinoDialog(
        context: context,
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
            title: Text("提示"),
            content: Column(
              children: <Widget>[
                SizedBox(
                  height: 10,
                ),
                Align(
                  child: Text(
                    "您确定要删除该条评论？",
                    style: TextStyle(fontSize: 16),
                  ),
                  alignment: Alignment(0, 0),
                ),
              ],
            ),
            actions: <Widget>[
              CupertinoDialogAction(
                child: Text("取消"),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              CupertinoDialogAction(
                child: Text("确定"),
                onPressed: () {
                  Navigator.pop(context);
                  _delReply(replyId);
                },
              ),
            ],
          );
        });
  }

  ///删除回复
  void _delReply(String replyId) {
    setState(() {
      _msg = "删除中...";
      _loading = true;
    });
    String url = "${Api.URL_REPLY_DEL}?replyId=$replyId";
    Http.get(url, successCallBack: (data) {
      setState(() {
        _loading = false;
      });
      _getReplys();
    }, errorCallBack: (error) {
      setState(() {
        _loading = false;
      });
      Toast.show("删除失败");
    });
  }

  ///关注用户
  void _followUser() async {
    setState(() {
      _msg = "操作中...";
      _loading = true;
    });
    String url = "${Api.URL_FOLLOW_ADD}?userId=${_topic.userId}";
    Http.post(url, successCallBack: (data) {
      Toast.show("操作成功");
      setState(() {
        _loading = false;
        isFollow = !isFollow;
      });
    }, errorCallBack: (error) {
      Toast.show(error);
      setState(() {
        _loading = false;
      });
    });
  }

  ///是否已关注
  void _isFollow() async {
    String url = "${Api.URL_FOLLOW_FOLLOWED}?userId=${_topic.userId}";
    Http.get(url, successCallBack: (data) {
      if (json.decode(data)["isFollow"] == "Y") {
        setState(() {
          isFollow = true;
        });
      }
    }, errorCallBack: (error) {
      setState(() {
        _loading = false;
      });
    });
  }

  void _update(String topicId, int praise) {
    Map<String, String> params = Map();
    params["topicId"] = topicId;
    params["praiseCount"] = "$praise";
    Http.post(Api.URL_TOPIC_UPDATE, params: params);
  }
}
